package com.travel.server.manager.impl.command.message;

import com.travel.common.CommonConstant;
import com.travel.common.util.CollectionUtil;
import com.travel.server.manager.dto.request.PageRequest;
import com.travel.server.manager.dto.response.message.QueryMessageMsgListResponse;
import com.travel.server.manager.dto.response.message.QueryMessageMsgListResponse.MsgItem;
import com.travel.server.manager.impl.command.AbstractCommand;
import com.travel.server.manager.impl.dal.MessageDal;
import com.travel.server.manager.impl.dal.MessageDal.MessageParam;
import com.travel.server.manager.impl.dal.PageDto;
import com.travel.server.manager.impl.enums.MessageExamStateEnum;
import com.travel.server.manager.impl.enums.MessageTemplateEnum;
import com.travel.server.manager.model.MessageTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: LiZhenhui
 * @Date: 2018\11\15 0015 22:21
 * @Desc:
 */
@Component
@Slf4j
public class QueryMessageMsgListCommand extends AbstractCommand<PageRequest, QueryMessageMsgListResponse> {

    @Autowired
    private MessageDal messageDal;

    @Override
    protected void checkInput(PageRequest request) {
        checkPageInput(request);
    }

    @Override
    public QueryMessageMsgListResponse handle(PageRequest request) {
        checkPageInput(request);
        MessageParam messageParam = makeParam(request);
        PageDto<MessageTemplate> pageDto = messageDal.select(messageParam);
        return makeResponse(pageDto);
    }

    private QueryMessageMsgListResponse makeResponse(PageDto<MessageTemplate> pageDto){
        QueryMessageMsgListResponse response = new QueryMessageMsgListResponse();
        List<MsgItem> msgList = new ArrayList<>();
        int total = pageDto.getTotal();
        List<MessageTemplate> list = pageDto.getList();
        if(!CollectionUtil.isEmpty(list)){
            for(MessageTemplate message : list){
                MsgItem item = new MsgItem();
                item.setContent(message.getMessageContent());
                item.setId(message.getId());
                item.setName(message.getMessageTitle());
                item.setSign(message.getMessageSign());
                item.setType(message.getMessageType() + CommonConstant.EMPTY_STR);
                item.setState(MessageExamStateEnum.getByState(message.getExamState()));
                msgList.add(item);
            }
        }
        response.setMessageList(msgList);
        response.setTotalNum(total);
        return response;
    }

    private MessageParam makeParam(PageRequest request){
        MessageParam param = new MessageDal.MessageParam();
        param.setType(MessageTemplateEnum.MSG.getType());
        param.setLimit(request.getLimit());
        param.setOffset(request.getOffset());
        return param;
    }
}
